<template>
  <div class="redBook">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="笔记Id">
        <el-input v-model="formInline.noteId" placeholder="笔记Id" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="商品ID">
        <el-input v-model="formInline.shopId" placeholder="商品ID" style="width: 300px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="insertShopData">插入表格</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="redBooKQueryHandler">刷新</el-button>
      </el-form-item>
      <el-form-item label="小红书token" style="position: relative; left: 200px;">
        <el-input v-model="formInline.redBookToken" placeholder="小红书token" style="width: 300px;" />
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%;" @row-click="handleDblClick">
      <el-table-column prop="noteId" label="笔记Id" width="250" />
      <el-table-column prop="shopId" label="商品Id" width="250" />
      <el-table-column prop="shopTitle" label="商品标题" width="800" />
      <el-table-column label="商品图片" width="150" v-slot="scope">
        <el-image
            preview-teleported
            style="width: 100px; height: 100px; cursor: zoom-in"
            :src="'data:image/jpeg;base64,' + scope.row.imageMain"
            :preview-src-list="previewSrcList"
        />
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template #default="scope">
          <!--          <el-button @click="getDownload(scope.row, 0)" type="primary" size="small">全部获取</el-button>-->
          <el-button @click="getDownload(scope.row, 1)" type="success" size="small">获取商品</el-button>
          <el-button @click="getDownload(scope.row, 2)" type="success" size="small">获取笔记</el-button>
          <el-button @click="getDownloadZip(scope.row, 1)" size="small">下载zip到本地</el-button>
          <el-button @click="deletes(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 可选：自定义图片查看器 -->
    <el-image-viewer
        v-if="imageViewerVisible"
        :url-list="imageViewerList"
        @close="imageViewerVisible = false"
    />
  </div>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import ElImageViewer, {ElMessage} from 'element-plus'
import 'element-plus/es/components/message/style/css'

import {
  deletes as apiDelete,
  download,
  downloadZip,
  getForWordUrl,
  queryByShopId,
  redBooKInsert,
  redBooKQuery
} from '/src/api/newsTop'

const formInline = ref({
  noteId: '',
  shopId: '',
  redBookToken: ''
})

const tableData = ref([])
const previewSrcList = ref([])

// 监听 token 改变自动存储
watch(() => formInline.value.redBookToken, (newVal) => {
  localStorage.setItem('redBookToken', newVal)
})

// 提取 shopId（从商品链接中提取 ID）
watch(() => formInline.value.shopId, (newVal) => {
  const regex = /goods-detail\/([a-zA-Z0-9]+)/;
  const match = newVal.match(regex);
  if (match && match[1]) {
    formInline.value.shopId = match[1]
  }
})

// 从链接中提取 noteId 和 token
watch(() => formInline.value.noteId, (newVal) => {
  if (!newVal) return
  const { noteId, token } = extractNoteIdAndToken(newVal)
  if (noteId) formInline.value.noteId = noteId
  if (token) formInline.value.redBookToken = token
})

function extractNoteIdAndToken(url) {
  let noteId = ''
  let token = ''
  const noteIdMatch = url.match(/\/item\/([a-zA-Z0-9]+)/)
  if (noteIdMatch) noteId = noteIdMatch[1]
  try {
    const urlObj = new URL(url)
    token = urlObj.searchParams.get('xsec_token') || ''
  } catch (e) {}
  return { noteId, token }
}

// 控制图片查看器（可选）
const imageViewerVisible = ref(false)
const imageViewerList = ref([])

async function handleDblClick(row) {
  try {
    previewSrcList.value = []

    const param = { shopNo: row.shopId }
    const res = await queryByShopId(param)
    const dataList = res.data.data || []

    const images = dataList.map(item => `data:image/jpeg;base64,${item.imageBase64}`)
    previewSrcList.value = images

    // 如需启用弹出式 imageViewer：
    // imageViewerList.value = images
    // imageViewerVisible.value = true
  } catch (err) {
    ElMessage.error('加载图片失败')
    console.error(err)
  }
}

const getDownload = (row, type) => {
  row.type = type
  const param = {
    strName: formInline.value.redBookToken,
    param: row
  }
  download(param).then(() => {
    ElMessage.success('下载成功')
    redBooKQueryHandler()
  }).catch(() => {
    ElMessage.error('下载失败')
  })
}

const getDownloadZip = (row, type) => {
  row.type = type
  // let shopIdOrNoteId = row.shopId == null ? row.noteId : row.shopId
  downloadZip(row).then((response) => {
    if (response.data == null) {
      ElMessage.error('下载Zip 失败')
      return
    }
    // 创建一个 URL 对象用于下载
    const url = window.URL.createObjectURL(new Blob([response.data]));

    // 创建一个临时的 a 标签来触发下载
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', row.shopTitle == null ? 'folder.zip' : row.shopTitle + ".zip");  // 你可以根据需要设置文件名
    document.body.appendChild(link);
    link.click();  // 触发点击事件下载文件
    document.body.removeChild(link);  // 下载后移除临时 a 标签
    ElMessage.success('下载Zip 成功')
  }).catch(() => {
    ElMessage.error('下载Zip 失败')
  })
}

const insertShopData = () => {
  // 直接截取地址 得到重定向地址
  const strNoteId = formInline.value.noteId;
  if (strNoteId) {
    let noteId = strNoteId.match(/https?:\/\/xhslink\.com\/\S+/);
    if (noteId == null) {
      const match = strNoteId.match(/explore\/([0-9a-f]{24})/i);
      if (match) {
        noteId = [match[1]]; // 用 ID 替换成第1个捕获组
      }
    }
    formInline.value.noteId = noteId ? noteId[0] : null;
    console.log(formInline.value.noteId); // 输出 685b628d000000001c031ba3
  }

  let strShopId = formInline.value.shopId;
  if (strShopId) {
    let shopId = strShopId.match(/https?:\/\/xhslink\.com\/\S+/);
    if (shopId == null) {
      const match = strShopId.match(/goods-detail\/([a-f0-9]{24})/);
      if (match) {
        shopId = [match[1]]; // 用 ID 替换成第1个捕获组
      }
    }
    formInline.value.shopId = shopId ? shopId[0] : null;
    console.log(formInline.value.shopId); // 输出 685b628d000000001c031ba3
  }

  getForWordUrl(formInline.value).then(res => {
    console.log(res.data.data)
    formInline.value.noteId = res.data.data.noteId
    formInline.value.shopId = res.data.data.shopId
    setTimeout(() => {
      redBooKInsert(formInline.value).then(res => {
        ElMessage.success(res.data.data)
        redBooKQueryHandler()
      }).catch(() => {
        ElMessage.error('插入失败')
      })
    }, 1000)

  }).catch(() => {
  })


}

const redBooKQueryHandler = () => {
  redBooKQuery({ param: formInline.value }).then(res => {
    tableData.value = res.data.data
  }).catch(() => {
    ElMessage.error('查询失败')
  })
}

const deletes = (row) => {
  apiDelete(row).then(res => {
    ElMessage.success(res.data.data)
    redBooKQueryHandler()
  }).catch(() => {
    ElMessage.error('删除失败')
  })
}

onMounted(() => {
  formInline.value.redBookToken = localStorage.getItem('redBookToken') || ''
  redBooKQueryHandler()
})
</script>

<style scoped>
.el-image {
  border: none;
  background-color: #f9f9f9;
  object-fit: cover;
  transition: all 0.3s ease;
  cursor: pointer;
}

.el-image:hover {
  transform: scale(1.02);
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.15);
}
</style>
